import { NameSpace } from 'utils/index';
import { Message } from '@teamix/ui';
import exceed from 'utils/apimap';
import { postServiceLog } from 'api';
import intl from '../../../../../../../../../locale';

const ns = NameSpace('merge-settings');
export const RECEIVE_MERGE_DATA = ns('RECEIVE_MERGE_DATA');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RESET_STATE = ns('RESET_STATE');

const { pathResource } = window.FORCE;

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function resetState() {
  return (dispatch) => {
    dispatch({
      type: RESET_STATE,
    });
  };
}

// 查询数据
export function getMergeRequest() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'project.settings.merge_requests.get',
        params: {
          id: pathResource.id,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_MERGE_DATA,
          data: result,
        });
      });
  };
}

export function getFormData(data) {
  return (dispatch) => {
    dispatch({
      type: RECEIVE_MERGE_DATA,
      data,
    });
  };
}
// 修改设置后保存
export function onFormSave(formData, cb) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'project.settings.merge_requests.put',
        params: {
          id: pathResource.id,
        },

        data: formData,
      })
      .then(() => {
        Message.success({
          title: intl.get({
            id: 'code-assets.settingsMergerequests.actions.MergeRequestUpdated',
            defaultMessage: '合并请求更新成功',
          }),
        });

        dispatch(getMergeRequest());
        cb && cb();
      });
    // .fail(() => {
    //   // 接口报错也要回调，以让按钮取消loading状态
    //   cb && cb('isFail');
    // });
  };
}

// 开启或者关闭服务
export function toogleService(params) {
  return () => {
    postServiceLog(params)
      .then(() => {})
      .catch((err) => {
        console.error(err);
      });
  };
}
